package com.lincoln.framework.common;

import com.lincoln.framework.utils.ConfigSetting;
import com.lincoln.framework.utils.MD5;

import java.util.*;

/**
 * 生成checksum工具类
 * @author ssx
 */
public class ChecksumUtils {
	
	private ChecksumUtils() {
		
	}
	
	/**
	 * 参数转换
	 * @param paramsMap
	 * @return
	 */
	private static Map<String, String> formatRequestMap(Map<String, String[]> paramsMap) {
		Map<String, String> transMap = new HashMap<String, String>();
		for (String key : paramsMap.keySet()) {
			String value = paramsMap.get(key)[0];
			transMap.put(key, value);
		}
		return transMap;
	}
	
	/**
	 * 生成checksum
	 * @param paramsMap
	 * @return
	 */
	public static String getCheckSum(Map<String, String[]> paramsMap) {
		Map<String, String> transMap = formatRequestMap(paramsMap);
		transMap.put("key", ConfigSetting.API_CHECKSUM_KEY);
		List paramList = sort(transMap);

		String paramString = "";
		Iterator itr = paramList.iterator();
		while (itr.hasNext()) {
			String key = itr.next().toString();
			if (key.equals("checksum")) {
				continue;
			}
			
			String value = transMap.get(key);
			paramString += "&" + key + "=" + value;
		}
		
		return MD5.hex_md5(paramString);
	}
	
	/**
	 * 对Map类型数据按Key排序
	 * 
	 * @param map
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static List sort(Map map) {
		List list = new ArrayList(map.keySet());
		Collections.sort(list, new Comparator() {
			public int compare(Object a, Object b) {
				//将key排在最后一位
				if (a.toString().equals("key")) {
					return 1;
				}
				if (b.toString().equals("key")) {
					return -1;
				}
				//将from排在倒数第二位
				if (a.toString().equals("from")) {
					return 1;
				}
				if (b.toString().equals("from")) {
					return -1;
				}
				return a.toString().toLowerCase().compareTo(b.toString().toLowerCase());
			}
		});
		return list;
	}
	
}
